<?php
namespace app\controllers;

use yii\web\Controller;
use Yii;
use app\common\Util;
use app\models\User;

class UserController extends Controller{
     public  $enableCsrfValidation = false;
     // 爬虫 教务的个人信息
	 public function actionIndex(){
	     // 检查提交方式
	     if(Yii::$app->request->isPost){
		 // 获取数据
		 $postData = Yii::$app->request->post();

		 // 检查缓存
		 $result = Yii::$app->redis->keys($postData['number'].'_'.$postData['type'].'_*'); // 获取缓存数据   
                 $time = NULL;
		 if($result){
			$array_result = explode('_',$result[0]); // 获取缓存写入时间
			$time = time() - intval($array_result[2]);// 计算相隔时间
		}
	         $unUpdate = $time < 500 ? TRUE : FALSE; // 判断是否需要更新，500秒自动更新
           	
		 if( $result && $unUpdate ){
		     // 缓存存在数据 且 不需要更新
		     $data = Yii::$app->redis->get($result[0]);
		     $data = json_decode($data,true);
		     echo json_encode( array('error'=>0,'data'=>$data) );
	        }else{
		      // 获取新的数据
		     $cookie = Util::LoginSchool($postData['number'],$postData['password']); // 模拟登录      
	             $data = $this->getHtmlStInfo($cookie); // 获取个人信息
			
	  /**       		// 判断是否获取数据成功
	         		if($data){ 
					Yii::$app->redis->del(@$result[0]); // 删除缓存数据
				}else{
					$data = Yii::$app->redis->get($result[0]); // 获取之前的缓存
				}            */			
	         		
		 // 写入缓存（更新数据/更新最新时间）
		 if( $data && !Yii::$app->redis->set( $postData['number'].'_'.$postData['type'].'_'.time(), json_encode($data) ) ){
		   Yii::info($postData['number'].'_'.$postData['type'].'____写入缓存失败', 'redis');
		}
		 // 返回数据			
		   echo json_encode( array('error'=>0,'message' => '获取个人信息成功','data'=>$data) );
			}

		}else{
			echo json_encode( array('error'=>1,'data'=>'提交数据方式有误') );
		}
	}

	public function getHtmlStInfo($cookie){

	        $url_StInfo = Yii::$app->params['URL']['STINFO']; // 个人信息url
		$html_StInfo = Util::getByCookie($url_StInfo, $cookie); // 提交请求

		$html_StInfo = Util::deal_str($html_StInfo); // 格式化返回结果
		$html_StInfo = Util::strip_html_tags(array('br'),$html_StInfo); //删除<br>标签
		

		$data = array();

		//姓名
        $partten_3 = '/<td align="center"  style="border:1px solid black" >&nbsp;(.*?)<\/td>/';
        preg_match_all($partten_3, $html_StInfo, $dataPartten);
        $data['name'] = $dataPartten[1][0];

		// 学院 专业 学号
		$partten_1 = '/<td align="center"  style="border:0px solid black"  colspan="2">(.*?)<\/td>/';
		preg_match_all($partten_1, $html_StInfo, $dataPartten);

		$data = $this->dealData($data, 'college', $dataPartten[1][0]);
		$data = $this->dealData($data, 'major', $dataPartten[1][1]);
		$data = $this->dealData($data, 'number', $dataPartten[1][2]);

		// 学制 班级
		$partten_2 = '/<td align="center"  style="border:0px solid black" >(.*?)<\/td>/';
		preg_match_all($partten_2, $html_StInfo, $dataPartten);

		$data = $this->dealData($data, 'length', $dataPartten[1][0]);
		$data = $this->dealData($data, 'class', $dataPartten[1][1]);
		return $data;
	}
	
	public function dealData($newData, $name, $data){
        	$tempData = explode("：", $data);
                $newData[$name] = $tempData[1];       
                return $newData;  
	}

	public function actionGetnupabyopenid(){
		
		if(Yii::$app->request->isPost){
			$postData = Yii::$app->request->post(); 
			
			$result = Yii::$app->redis->keys($postData['openId'].'_*'); // 获取缓存数据
			$time = NULL;
			if($result){
				$array_result = explode('_',$result[0]); // 获取缓存写入时间
				$time = time() - intval($array_result[1]);// 计算相隔时间
			}
		    $unUpdate = $time < 5 ? TRUE : FALSE; // 判断是否需要更新，500秒自动更新
		   //     var_dump($result);			
			if( $result && $unUpdate ){
				// 缓存存在数据 且 不需要更新
				$data = Yii::$app->redis->get($result[0]);
				$data = json_decode($data,true);
				echo json_encode( array('error'=>0,'data'=>$data) );
			}else{
				// 获取新的数据
				$model = new User;	
				$data = $model->getNuPaByOpenId($postData['openId']);
				
				// 判断是否获取数据成功
				if($data){ 
					Yii::$app->redis->DEL(@$result[0]); // 删除缓存数据
				}else{
					$data = Yii::$app->redis->get(@$result[0]); // 获取之前的缓存
				}			
				
				// 写入缓存（更新数据/更新最新时间）
				if( $data && !Yii::$app->redis->set( $postData['openId'].'_'.time(), json_encode($data) ) ){
					Yii::info($postData['number'].'____写入缓存失败', 'redis');
				}
				
				// 返回数据			
				if($data){
					echo json_encode( array('error'=>0,'data'=>$data) );
				}else{
					echo json_encode( array('error'=>1,'data'=>'暂时无法提供数据，请联系小程序管理员') );
				}
			}   
		}else{
			echo json_encode( array('error'=>1,'data'=>'提交数据方式有误') );
		}
	}

	// 绑定/更新
	public function actionBind(){
		
		if(Yii::$app->request->isPost){

			$model = new User;	
			$postData = Yii::$app->request->post(); // 获取数据
			
			// 检查账号和密码有无错误
		       $cookie = Util::LoginSchool($postData['number'],$postData['password']); // 模拟登录
			
                        if($cookie){
			// 防止用户重复提交数据，先对比数据库之前的数据
			$data = $model->getNuPaByOpenId($postData['openId']);	
			if( $data && $data['number'] == $postData['number'] && $data['password'] == $postData['password']){                      
                        $data = $model->updateAll(['state' => 1],'openid = :openid',[':openid' => $postData['openId']]);
		        echo json_encode( array('error'=>0,'data'=>'已经保存成功了哦~') );	
			          Yii::$app->end();
			}
                               
		    // 检查之前是否有资料，进行更新还是插入操作
			if($data){
				// 数据库已经存在资料，需要更新
				$sqlResult = $model->updateNuPa($postData);
			}else{
				// 数据不存在资料，需要插入
				$sqlResult = $model->insertNuPa($postData);
			}
              }  
                  //      var_dump($sqlResult);
			// 写缓存
			if($sqlResult == 0){	
				$result = Yii::$app->redis->keys($postData['openId'].'_*'); // 获取缓存数据
				if($result){		
					Yii::$app->redis->del($result[0]); // 删除缓存数据	
				}
				// 写入缓存（更新数据/更新最新时间）
				if( !Yii::$app->redis->set( $postData['openId'].'_'.time(), json_encode($postData) ) ){
					Yii::info($postData['number'].'____写入缓存失败', 'redis');
				}
			}    

			// 返回信息
			if($sqlResult == 0){
				echo json_encode( array('error'=>0,'data'=>'更新数据成功') );	
			}else{
                               
			     	echo json_encode( array('error'=>1,'data'=>'更新数据失败') );
			}
		}else{
			echo json_encode( array('error'=>1,'data'=>'提交数据方式有误') );
		}
	}

	// 解绑
	public function actionUnbind(){
		
		if(Yii::$app->request->isPost){

			$model = new User;	
			$postData = Yii::$app->request->post(); // 获取数据
			
			// 判断用户之前是不是绑定过，预防不测
			$data = $model->getNuPaByOpenId($postData['openId']);	
			if( !$data ){
				echo json_encode( array('error'=>1,'data'=>'绑定了才有解绑功能哦~') );	
				Yii::$app->end();
			}

			// 进行解绑
			$sqlResult = $model->updateState($data);
	
			$result_1 = Yii::$app->redis->keys($postData['openId'].'_*'); // 获取相关缓存数据
			$result_2 = Yii::$app->redis->keys($data['number'].'_*'); // 获取相关缓存数据
			if( $sqlResult && ($result_1 || $result_2) ){		
				for($i=0; $i<count($result_1); $i++){
					Yii::$app->redis->del($result_1[$i]); // 删除缓存数据
				}
				for($i=0; $i<count($result_2); $i++){
					Yii::$app->redis->del($result_2[$i]); // 删除缓存数据
				}
			}
			
			// 返回提示
			if($sqlResult){
				echo json_encode( array('error'=>0,'data'=>'解绑成功') );	
			}else{
				echo json_encode( array('error'=>1,'data'=>'解绑失败') );
			}

		}else{
			echo json_encode( array('error'=>1,'data'=>'提交数据方式有误') );
		}

	 }
 
         //返回user表信息给前端
       public function actionGet(){
            $model = new User();
            if(Yii::$app->request->isPost){
                $postData = Yii::$app->request->post();
                $openid = $postData['openId'];
                $sql = "select openid,number,score,identity,topicCount,testTime,nickname,avatarUrl,state from freshmanHelper_user where openid = '$openid'";
                $data = User::findBysql($sql)->asArray()->all();
                echo json_encode(array('error' => 0,'message' => 'success','data' => $data,));
             }
         }                
        //更新user表数据
       public function actionAdd(){
            $model = new User();
            if(Yii::$app->request->isPost){
                $postData = Yii::$app->request->post();
                $identity = $postData['nianji'];
                $score = $postData['score'];
                $topicCount = $postData['topicCount'];
                $openid = $postData['openId'];
                $data = $model ->updateAll(['score' => $score,'topicCount' => $topicCount,'identity' => $identity],'openid = :openid and state = :state',[':openid' => $openid,':state' => '1']);
                echo json_encode(array('error' => 0, 'message' => 'success', 'data' => $data,));
               }
          }  
      //排行榜 
       public function actionRank(){
            $model = new User();
            if(Yii::$app->request->isPost){
               $postData = Yii::$app->request->post();
               $identity = $postData['identity'];
               if( $identity == 19 ){
               $sql = "select openid,number,score,topicCount,identity,nickname,avatarUrl from freshmanHelper_user where score != 0 and identity = $identity order by score desc limit 30";
               $data = User::findBysql($sql)->asArray()->all(); 
               echo json_encode(array('error' => 0, 'message' => '新生前30名排行榜','data' => $data,));
                  Yii::$app->end();
         }else{
               $sql = "select openid,number,score,topicCount,identity,nickname,avatarUrl from freshmanHelper_user where score != 0 and (identity = '18' or identity = '17' or identity = '16' or identity = '15' or identity = '14' or identity = '13') order by score desc limit 30";
               $data = User::findBysql($sql)->asArray()->all();
               echo json_encode(array('error' => 0, 'message' => '老生前30名排行榜','data' => $data,));
             }
       }
          exit(0);
 }
       
       //更新用户答题时间
     public function actionUptime(){
         $model = new User();
         if(Yii::$app->request->isPost){
            $postData = Yii::$app->request->post();
            $openid = $postData['openId'];
            $testTime = $postData['time'];
            $data = $model ->updateAll(['testTime' => $testTime],'openid = :openid and state = :state',[':openid' => $openid,':state' => '1']);
            echo json_encode(array('error' => 0, 'message' => 'success', 'data' => $data,));
          }
     }
}       

